/**package com.abc.recycling.controller.admin;

import com.abc.recycling.model.User;
import com.abc.recycling.service.UserService;
import com.abc.recycling.service.OrderService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Controller
@RequestMapping("/admin/residents")
@PreAuthorize("hasRole('ADMIN')")
@RequiredArgsConstructor
public class AdminResidentController {

    private final UserService userService;
    private final OrderService orderService;
    private static final int PAGE_SIZE = 10;

    @GetMapping({"", "/"})
    public String listResidents(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) Integer status,
            Model model) {
        try {
            log.info("获取居民列表: page={}, keyword={}, status={}", page, keyword, status);
            
            // 获取分页数据
            PageRequest pageRequest = PageRequest.of(page - 1, PAGE_SIZE);
            Page<User> residentPage = userService.getResidentsByPage(keyword, status, pageRequest);
            
            // 获取统计数据
            long totalResidents = userService.countResidentsByRole();
            long activeResidents = userService.countActiveResidents();
            long monthlyOrders = orderService.countOrdersByDate(LocalDateTime.now().withDayOfMonth(1));
            double monthlyWeight = orderService.getTotalWeight();
            
            // 添加数据到模型
            model.addAttribute("residents", residentPage.getContent());
            model.addAttribute("currentPage", page);
            model.addAttribute("totalPages", residentPage.getTotalPages());
            model.addAttribute("totalResidents", totalResidents);
            model.addAttribute("activeResidents", activeResidents);
            model.addAttribute("monthlyOrders", monthlyOrders);
            model.addAttribute("monthlyWeight", monthlyWeight);
            
            log.info("居民列表数据加载完成");
            return "admin/resident/list";
        } catch (Exception e) {
            log.error("获取居民列表失败", e);
            throw e;
        }
    }

    @GetMapping("/{id}")
    @ResponseBody
    public ResponseEntity<?> getResident(@PathVariable Long id) {
        try {
            log.info("获取居民详情: id={}", id);
            User resident = userService.getUserById(id);
            if (resident == null) {
                Map<String, String> error = new HashMap<>();
                error.put("error", "居民不存在");
                return ResponseEntity.notFound().build();
            }
            
            // 获取居民相关的统计数据
            Map<String, Object> data = new HashMap<>();
            data.put("id", resident.getId());
            data.put("username", resident.getUsername());
            data.put("realName", resident.getRealName());
            data.put("phone", resident.getPhone());
            data.put("email", resident.getEmail());
            data.put("address", resident.getAddress());
            data.put("status", resident.getStatus());
            data.put("createTime", resident.getCreateTime());
            data.put("totalOrders", orderService.countOrdersByUser(id));
            data.put("monthlyOrders", orderService.countOrdersByDate(LocalDateTime.now().withDayOfMonth(1)));
            
            log.info("居民详情数据获取成功");
            return ResponseEntity.ok(data);
        } catch (Exception e) {
            Map<String, String> error = new HashMap<>();
            error.put("error", e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }

    @PostMapping("/save")
    @ResponseBody
    public ResponseEntity<Object> saveResident(@RequestBody User resident) {
        try {
            log.info("保存居民信息: {}", resident);
            if (resident.getId() == null) {
                resident.setRole("RESIDENT");
                resident = userService.createUser(resident);
            } else {
                userService.updateUser(resident);
            }
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "保存成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("保存居民信息失败: ", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @DeleteMapping("/{id}")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> deleteResident(@PathVariable Long id) {
        try {
            log.info("删除居民: id={}", id);
            userService.deleteUser(id);
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }

    @PostMapping("/{id}/reset-password")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> resetPassword(
            @PathVariable Long id,
            @RequestBody Map<String, String> body) {
        try {
            log.info("重置居民密码: id={}", id);
            String newPassword = body.get("newPassword");
            userService.resetPassword(id, newPassword);
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }

    @GetMapping("/export")
    public ResponseEntity<byte[]> exportResidents(
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) Integer status) {
        try {
            log.info("导出居民数据: keyword={}, status={}", keyword, status);
            List<User> residents = userService.searchUsers("RESIDENT", keyword);
            // TODO: 实现导出逻辑
            return ResponseEntity.ok()
                    .header("Content-Type", "application/vnd.ms-excel")
                    .header("Content-Disposition", "attachment; filename=residents.xlsx")
                    .body(new byte[0]);
        } catch (Exception e) {
            log.error("导出居民数据失败", e);
            return ResponseEntity.badRequest().build();
        }
    }
} */